package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.fiegn.EmailServiceFeign;
import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.service.LagouAuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.Random;

@Service
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {

    //验证码有效时间
    private long termOfValidity=60*1000*10;

    @Resource
    EmailServiceFeign emailServiceFeign;

    @Resource
    LagouAuthCodeDao lagouAuthCodeDao;

    @Override
    @Transactional
    public boolean create(String email) {
        //获得六位随机码
        String code =String.format("%06d", new Random().nextInt(1000000));
        lagouAuthCodeDao.save(LagouAuthCode.builder()
                .code(code)
                .email(email)
                .createtime(new Date())
                .expiretime(new Date(System.currentTimeMillis()+termOfValidity)).build());
        return emailServiceFeign.send(email,code);
    }

    @Override
    public int validate(String email, String code) {

        LagouAuthCode authCode = lagouAuthCodeDao.getByEmailAndCodeByExpiretimeDesc(email, code);
        if(authCode==null){
            return 1;
        }
        return authCode.getExpiretime().getTime()>System.currentTimeMillis()?0:2;
    }


//    @Autowired
//    private LagouAuthCodeDao resumeDao;
//
//    @Override
//    public Resume findDefaultResumeByUserId(Long userId) {
//        Resume resume = new Resume();
//        resume.setUserId(userId);
//        // 查询默认简历
//        resume.setIsDefault(1);
//        Example<Resume> example = Example.of(resume);
//        return resumeDao.findOne(example).get();
//    }



}
